#!/bin/bash
#
# Transport that uses the scp(1) command to copy files
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 20 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## p_transport_scp_can_download <url>
##
## Determines if the scp transport can download <url>. Returns 0 if the
## transport is able to handle the <url>, non-zero otherwise.
##
function p_transport_scp_can_download() {
	local status=0
	local chk=
	local filename=
	
	which scp > /dev/null 2>&1
	status=$?
	
	if [[ ${status} -eq 0 ]]; then
		# Have the scp command: check to see if this is a true URL
		chk=$(echo "$1" | grep '://')
		if [[ -n "${chk}" ]]; then
			# Check to see if this is a file:// or scp:// URL
			status=1
			for proto in "file" "scp"; do
				chk=$(echo "$1" | grep ^${proto}://)
				if [[ -n "${chk}" ]]; then
					status=0
					break
				fi
			done
		else
			# Not a URL: check if we have a local absolute path
			chk=$(echo "$1" | grep ^/)
			if [[ -z "${chk}" ]]; then
				# OK, see if this has a prefix:/absolute path
				chk=$(echo "$1" | grep ':/')
				if [[ -z "${chk}" ]]; then
					# This URL is something else
					status=1
				fi
			else
				filename="$1"
			fi
		fi
		
		# One final test: if we do have something that looks like a file,
		# make sure it actually exists and is a readable file (not a directory)
		if [[ -n "${filename}" ]]; then
			if [[ -r "${filename}" ]]; then
				if [[ -d "${filename}" ]]; then
					# Can only copy a file, not a directory
					status=1
				fi
			else
				# unreadable
				status=1
			fi
		fi
	fi
	
	return ${status}
}


## p_transport_scp_download <url> <output file> <user agent>
##
## Copies a file from <url> to <output file> using scp. If <output file> is
## the special name "-", copies the file to a local temporary file and then
## cat's it. The <user agent> is ignored. Returns 0 on success, non-zero if
## an error occurs.
##
function p_transport_scp_download() {
	local status=0
	local url=$(echo "$1" | sed s~'^file://'~~ | sed s~'^scp://'~~)
	local tmpname=
	
	if [[ "$2" == "-" ]]; then
		tmpname=$(s_mktempfile)
		scp "${url}" "${tmpname}"
		status=$?
		
		if [[ ${status} -eq 0 ]]; then
			cat "${tmpname}"
		fi
	else
		scp "${url}" "$2"
		status=$?
	fi
	
	return ${status}
}
